package com.example.demo.auth;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthorizationHandler implements HandlerInterceptor {
    private AuthBus authBus;

    public AuthorizationHandler(AuthBus authBus) {
        this.authBus = authBus;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (request.getMethod().equals("OPTIONS")) {
            return true;
        }

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerImpl = (HandlerMethod) handler;
        Auth methodAnnotation = handlerImpl.getMethodAnnotation(Auth.class);

        if (methodAnnotation == null || methodAnnotation.isAllowAnonymous()) {
            return true;
        }

        AuthResult authResult = authBus.verify(request,handlerImpl);

        if(authResult.isVerify()){
            BaseUserInfo userInfo = authResult.getUserInfo();
            request.setAttribute(AuthHelper.AUTH_KEY_USER_INFO,userInfo);
            return true;
        }else {
            response.setStatus(authResult.getHttpStatus() ==null?401:authResult.getHttpStatus().value());
            response.setHeader("Access-Control-Allow-Origin", "*");//* or origin as u prefer
            response.setHeader("Access-Control-Allow-Credentials", "true");
            response.setHeader("Access-Control-Allow-Methods", "PUT, POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "content-type, authorization");
            response.setContentType("application/json");
            response.getWriter().write(authResult.getResultJson());
            return false;
        }
    }
}
